import 'dart:io';

import 'package:dio/dio.dart';
import 'package:get/get.dart' as my_get;
import 'package:o2oa_all_platform/common/extension/index.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:path/path.dart' as path;

import '../../../../common/api/index.dart';
import '../../../../common/models/index.dart';
import '../../../../common/routers/index.dart';
import '../../../../common/utils/index.dart';
import '../../../apps/cms/cms_document/index.dart';
import '../../../apps/meeting/meeting_detail/index.dart';
import '../../../common/inner_webview/index.dart';
import '../../../common/preview_image/index.dart';
import '../../../common/process_webview/index.dart';
import 'index.dart';

class InstantChatController extends my_get.GetxController {
  InstantChatController();

  final state = InstantChatState();
  Map<String, String> headers = {};

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    // 初始化数据
    headers[O2ApiManager.instance.tokenName] =
        O2ApiManager.instance.o2User?.token ?? '';
    var map = my_get.Get.arguments;
    if (map != null && map['instantMsgList'] != null) {
      state.instantMsgList.clear();
      state.instantMsgList.addAll(map['instantMsgList'] ?? []);
    } else {
      loadInstantMsgList();
    }
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  Future<void> loadInstantMsgList() async {
    final list = await MessageCommunicationService.to.myInstantMsgList(100);
    if (list == null || list.isEmpty) {
      return;
    }
    final newList = list.where((element) => element.type?.startsWith('im_') == false).toList(); // im 消息不显示
    state.instantMsgList.clear();
    state.instantMsgList.addAll(newList);
  }

  ///
  /// 系统消息点击
  ///
  void clickInstantItem(InstantMsg info) {
    final type = info.type;
    if (type == null) return;
    if (type.startsWith('task_') ||
        type.startsWith('taskCompleted_') ||
        type.startsWith('read_') ||
        type.startsWith('readCompleted_') ||
        type.startsWith('review_') ||
        type.startsWith('work_') ||
        type.startsWith('process_')) {
      _openWork(info.body);
    } else if (type.startsWith('meeting_')) {
      // 会议
      _openMeeting(info.body);
    } else if (type.startsWith('attendance_')) {
      _openAttendance(info.body);
    } else if (type.startsWith('calendar_')) {
      _openCalendar(info.body);
    } else if (type.startsWith('cms_')) {
      _openCms(info.body);
    } else if (type.startsWith('bbs_')) {
      _openBBS(info.body);
    } else if (type.startsWith('mind_')) {
      _openMindMap(info.body);
    } else if (info.isCustomType()) {
      final body =
          InstantCustomO2AppMsgBody.fromJson(O2Utils.parseStringToJson(info.body ?? '{}'));
      switch (body.o2AppMsg?.msgtype) {
        case 'text':
          final url = body.o2AppMsg?.text?.url;
          final openExternally = body.o2AppMsg?.text?.openExternally ?? false;
          _openUrlInner(url, openExternally: openExternally );
          break;
        case 'image':
          final url = body.o2AppMsg?.image?.url;
          _openImageWithUrl(url);
          break;
        case 'textcard':
          final url = body.o2AppMsg?.textcard?.url;
          final openExternally = body.o2AppMsg?.textcard?.openExternally ?? false;
          _openUrlInner(url, openExternally: openExternally);
          break;
      }
    }
  }

  /// 脑图
  _openMindMap(String? body) async {
    my_get.Get.toNamed(O2OARoutes.appMindMap);
  }

  /// 信息中心
  _openBBS(String? body) async {
    my_get.Get.toNamed(O2OARoutes.appBBS);
  }

  /// 信息中心
  _openCms(String? body) async {
    OLogger.d(body);
    if (body != null && body.isNotEmpty) {
      final doc = DocumentData.fromJson(O2Utils.parseStringToJson(body));
      if (doc.id != null && doc.id!.isNotEmpty) {
        // 打开对应的文档
        CmsDocumentPage.open(doc.id!, title: doc.title??'');
        return;
      }
    }
    // 打开信息中心
    my_get.Get.toNamed(O2OARoutes.appCms);
  }

  ///   日程
  _openCalendar(String? body) async {
    my_get.Get.toNamed(O2OARoutes.appCalendar);
  }

  /// 考勤
  _openAttendance(String? body) async {
    my_get.Get.toNamed(O2OARoutes.appAttendance);
  }
  // 会议
  _openMeeting(String? body) async {
    final meeting = MeetingInfoModel.fromJson(O2Utils.parseStringToJson(body ?? '{}'));
    if (meeting.id != null && meeting.id?.isNotEmpty == true) {
      MeetingDetailPage.openMeeting(meeting.id!);
    } else {
      my_get.Get.toNamed(O2OARoutes.appMeeting);
    }
  }

  /// 
  /// 打开在线图片
  /// 
  _openImageWithUrl(String? url) async {
    if (url == null || url.isEmpty) {
      return ;
    }
    final fileName = url.fileName();
    if (fileName.isEmpty) {
      return;
    }
    // 本地存储路径
    final tempFolder = await O2FilePathUtil.getTempFolderWithUrl(url);
    if (tempFolder == null || tempFolder.isEmpty) {
      return;
    }
    final filePath = path.join(tempFolder, fileName); // '$tempFolder/$fileName';
    var file = File(filePath);
    if (!file.existsSync()) {
      Loading.show();
      Response response = await O2HttpClient.instance.downloadFile(url, filePath);
      if (response.statusCode != 200) {
        Loading.showError('im_chat_error_download_file'.tr);
        if (file.existsSync()) {
          // 下载失败 删除文件
          file.delete();
        }
        return;
      }
      Loading.dismiss();
    }
    PreviewImagePage.open(filePath, fileName);
     
  }

  ///
  /// 打开工作页面
  ///
  _openWork(String? body) {
    final bodyMap = O2Utils.parseStringToJson(body ?? '{}');
    final work = bodyMap['work'] ?? '';
    final title = bodyMap['title'] ?? 'process_work_no_title_no_process'.tr;
    ProcessWebviewPage.open(work, title: title);
  }

  ///
  /// 外部浏览器打开
  ///
  _openUrlInner(String? url, {bool openExternally = false}) async {
    if (url != null && url.isNotEmpty) {
      if (openExternally) {
        Uri? uri = Uri.tryParse(url);
        if (uri!= null && await canLaunchUrl(uri)) {
          final result = await launchUrl(
            uri,
            mode: LaunchMode.externalApplication,
            webViewConfiguration: WebViewConfiguration(headers: <String, String>{
              O2ApiManager.instance.tokenName:
                  O2ApiManager.instance.o2User?.token ?? ''
            }),
          );
          if (!result) {
            OLogger.e('打开 url $url 失败！');
          }
        } else {
          OLogger.e('错误的 url ：$url');
          Loading.showError('common_error_url'.trArgs([url]));
        } 
      } else {
        InnerWebviewPage.open(url);
      }
    } else {
      OLogger.e('错误的 url ：$url');
      Loading.showError('common_error_url'.trArgs([url??'']));
    }
  }

  ///
  /// 消息图标
  ///
  String messageTypeAvatar(String type) {
    if (type.startsWith("task_")) {
      return O2NativeAppEnum.task.assetPath;
    } else if (type.startsWith("taskCompleted_")) {
      return O2NativeAppEnum.taskcompleted.assetPath;
    } else if (type.startsWith("read_")) {
      return O2NativeAppEnum.read.assetPath;
    } else if (type.startsWith("readCompleted_")) {
      return O2NativeAppEnum.readcompleted.assetPath;
    } else if (type.startsWith("review_") ||
        type.startsWith("work_") ||
        type.startsWith("process_")) {
      return O2NativeAppEnum.task.assetPath;
    } else if (type.startsWith("meeting_")) {
      return O2NativeAppEnum.meeting.assetPath;
    } else if (type.startsWith("calendar_")) {
      return O2NativeAppEnum.calendar.assetPath;
    } else if (type.startsWith("cms_")) {
      return O2NativeAppEnum.cms.assetPath;
    } else if (type.startsWith("bbs_")) {
      return O2NativeAppEnum.bbs.assetPath;
    } else if (type.startsWith("mind_")) {
      return O2NativeAppEnum.mindMap.assetPath;
    } else {
      return 'app_o2_ai.png';
    }
  }

  String? messageTypeName(String type) {
    if (type.startsWith("task_")) {
      return O2NativeAppEnum.task.name;
    } else if (type.startsWith("taskCompleted_")) {
      return O2NativeAppEnum.taskcompleted.name;
    } else if (type.startsWith("read_")) {
      return O2NativeAppEnum.read.name;
    } else if (type.startsWith("readCompleted_")) {
      return O2NativeAppEnum.readcompleted.name;
    } else if (type.startsWith("review_") ||
        type.startsWith("work_") ||
        type.startsWith("process_")) {
      return O2NativeAppEnum.task.name;
    } else if (type.startsWith("meeting_")) {
      return O2NativeAppEnum.meeting.name;
    } else if (type.startsWith("calendar_")) {
      return O2NativeAppEnum.calendar.name;
    } else if (type.startsWith("cms_")) {
      return O2NativeAppEnum.cms.name;
    } else if (type.startsWith("bbs_")) {
      return O2NativeAppEnum.bbs.name;
    } else if (type.startsWith("mind_")) {
      return O2NativeAppEnum.mindMap.name;
    } else {
      return null;
    }
  }
 
}
